package com.codepoorfish.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codepoorfish.anno.PassToken;
import com.codepoorfish.anno.UserLoginToken;
import com.codepoorfish.controller.utils.R;
import com.codepoorfish.domain.User;
import com.codepoorfish.service.UserService;
import com.codepoorfish.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @PassToken
    public R login(@RequestBody User user){
        User userOne = userService.getOne(new QueryWrapper<User>().eq("user_name", user.getUserName()).eq("password", user.getPassword()));
        Map<String, Object> jsonObject = new HashMap<>();
        if (userOne != null) {
            String token = new TokenUtil().getToken(user);
            System.out.println(token);
            jsonObject.put("token", token);
            jsonObject.put("user", userOne);
            System.out.println(jsonObject);
            return new R(true, "请求成功", jsonObject);
        } else {
            return new R(false, "用户名或密码错误");
        }
    }

    @PostMapping("/register")
    @PassToken
    public R register(@RequestBody User user) {
        userService.save(user);
        return new R(true, "注册成功");
    }

    @PostMapping("/update")
    @UserLoginToken
    public R update(@RequestBody User user) {
        if (userService.updateById(user)) {
            return new R(true, "更新成功");
        } else {
            return new R(false, "更新失败");
        }
    }

    @PostMapping("/updatePwd")
    @UserLoginToken
    public R updatePwd(@RequestBody User user, @RequestParam String oldPwd, @RequestParam String newPwd) {
        if (userService.getOne(new QueryWrapper<User>()
                .eq("user_name", user.getUserName())
                .eq("password", oldPwd)) != null) {
            user.setPassword(newPwd);
            userService.updateById(user);
            return new R(true, "修改成功");
        } else {
            return new R(false, "修改失败");
        }
    }
}
